package com.itheima.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import com.itheima.view.OrderView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

//体检预约
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private JedisPool jedisPool;

    //通过ID查询预约相关信息（体检人姓名，预约日期，套餐名称，预约类型）
    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        //处理日期格式
        if (map!=null){
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    //体检预约
    @Override
    public Result order(Map map) throws Exception {

        //**********分布式锁，防止用户多次点击发送两次相同请求***********
        //缺点：redis分布式锁会占用redis的内存，需要定时清理
        Jedis resource = jedisPool.getResource();
        //如果没有key则设置值
        String orderDate = (String) map.get("orderDate");//预约日期
        String telephone = (String) map.get("telephone");//获取用户页面输入手机号
        String setmealId = (String) map.get("setmealId");//套餐ID

        String resourceSet = resource.getSet(orderDate + ":" + telephone + ":" + setmealId, "QAQ");
        resource.expire(orderDate+":"+telephone+":"+setmealId,600);//设置过期时间10分钟

        //测试使用，让线程睡眠10秒
        //Thread.sleep(10000);

        if (StringUtils.isNotEmpty(resourceSet)){
            return new Result(false,"已预约该套餐辣，好好玩别瞎搞┑(￣Д ￣)┍");
        }
        //资源返回给jedispool
        resource.close();
        //**********分布式锁，防止用户多次点击发送两次相同请求***********


        //1.检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        //String orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting==null){
            //指定日期没有进行预约设置，无法完成体检预约
            return new Result(false,MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.检查用户所选择的日期是否已经预约满，如果预约满则无法预约
        //2.1获取可预约人数
        int number = orderSetting.getNumber();
        //2.2获取已预约人数
        int reservations = orderSetting.getReservations();
        if (reservations>=number){
            //已经预约满，无法预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }

        //3.检查用户是否重复预约（同一个用户名在同一天预约了同一个套餐），如果重复预约则无法完成再次预约
        //String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member!=null){
            //判断是否重复预约
            //3.1获取会员ID
            Integer memberId = member.getId();
            //3.2获取预约日期
            Date order_Date = DateUtils.parseString2Date(orderDate);
            //3.3获取套餐ID
            //String setmealId = (String) map.get("setmealId");
            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));
            //3.4根据条件查询
            List<Order> list = orderDao.findByCondition(order);
            if (list!=null && list.size()>0){
                //说明存在重复预约，无法再次完成预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }else {
            //4.检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String)map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String)map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            //自动完成会员注册
            memberDao.add(member);
        }
        //5.预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());  //设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));  //设置预约日期
        order.setOrderType((String) map.get("orderType"));  //设置预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO); //设置到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));    //套餐ID

        //新增修改点,将预约人及预约地址保存至数据库
        order.setOrderPerson((String) map.get("name"));
        order.setOrderAddress((String)map.get("address"));
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations()+1); //设置已预约人数
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        //预约成功并返回预约ID
        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用基于mybatis框架提供的PageHelper进行分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<OrderView> page = orderDao.findPage(queryString);
        //将Page对象转换为PageResult对象
        PageResult result = new PageResult(page.getTotal(), page.getResult());
        return result;
    }

    @Override
    public Result add(Order order, Integer[] setmealIds) {
        //1.日期判断,所选日期是否设置预约
        Date orderDate = order.getOrderDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = null;
        date = sdf.format(orderDate);
        Date date1 = null;
        try {
            date1 = DateUtils.parseString2Date(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        OrderSetting orderSetting = null;
        try {
            orderSetting = orderSettingDao.findByOrderDate(date1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (orderSetting==null){
            return new Result(false,MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2.查询是否预约满
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations>=number){
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        order.setSetmealId(setmealIds[0]);
        order.setOrderType("电话预约");
        order.setOrderStatus("未到诊");
        orderDao.add(order);

        //3.更新已预约数
        orderSetting.setReservations(orderSetting.getReservations()+1); //设置已预约人数
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true,MessageConstant.ORDER_SUCCESS);
    }

    @Override
    public void delete(Integer id) {
        Map map = orderDao.findById(id);
        Date orderDate = (Date) map.get("orderDate");
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(orderDate);
        orderDao.delete(id);
        orderSetting.setReservations(orderSetting.getReservations()-1); //设置已预约人数
        orderSettingDao.editReservationsByOrderDate(orderSetting);
    }

    @Override
    public PageResult findByDate(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String[] date = queryPageBean.getOrderDate();
        List<Date> orderDate = new ArrayList<>();
        for (String s : date) {
            try {
                Date d = DateUtils.parseString2Date(s);
                Calendar c = Calendar.getInstance();
                c.setTime(d);
                c.add(Calendar.DAY_OF_MONTH, 1);//利用Calendar 实现 Date日期+1天
                d = c.getTime();
                orderDate.add(d);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //使用基于mybatis框架提供的PageHelper进行分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<OrderView> page = orderDao.findByDate(orderDate.get(0),orderDate.get(1));
        //将Page对象转换为PageResult对象
        PageResult result = new PageResult(page.getTotal(), page.getResult());
        return result;
    }

    @Override
    public PageResult findByOrderType(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用基于mybatis框架提供的PageHelper进行分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<OrderView> page = orderDao.findByOrderType(queryString);
        //将Page对象转换为PageResult对象
        PageResult result = new PageResult(page.getTotal(), page.getResult());
        return result;
    }

    @Override
    public PageResult findByOrderStatus(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用基于mybatis框架提供的PageHelper进行分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<OrderView> page = orderDao.findByOrderStatus(queryString);
        //将Page对象转换为PageResult对象
        PageResult result = new PageResult(page.getTotal(), page.getResult());
        return result;
    }

    @Override
    public PageResult findByOrderString(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        //使用基于mybatis框架提供的PageHelper进行分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<OrderView> page = orderDao.findByOrderString(queryString);
        //将Page对象转换为PageResult对象
        PageResult result = new PageResult(page.getTotal(), page.getResult());
        return result;
    }

    @Override
    public List<Integer> findSetmealIdsByOrderId(Integer orderId) {
        List<Integer> setmealIds = orderDao.findSetmealIdsByOrderId(orderId);
        return setmealIds;
    }

    @Override
    public Result edit(Order order, Integer[] setmealId) {
        Date orderDate = order.getOrderDate();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = null;
        date = sdf.format(orderDate);
            //1.日期判断,所选日期是否设置预约
            Date date1 = null;
            try {
                date1 = DateUtils.parseString2Date(date);
            } catch (Exception e) {
                e.printStackTrace();
            }
            OrderSetting orderSetting = null;
            try {
                orderSetting = orderSettingDao.findByOrderDate(date1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (orderSetting == null) {
                return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }
            //2.查询是否预约满
            int number = orderSetting.getNumber();
            int reservations = orderSetting.getReservations();
            if (reservations >= number) {
                return new Result(false, MessageConstant.ORDER_FULL);
            }
            order.setSetmealId(setmealId[0]);
            orderDao.edit(order);
            orderSetting.setReservations(orderSetting.getReservations() + 1); //设置已预约人数
            orderSettingDao.editReservationsByOrderDate(orderSetting);
            return new Result(true, MessageConstant.ORDER_SUCCESS);
        }

    @Override
    public void changeOrderStatus(Integer id) {
        String Status = orderDao.findStatus(id);
        if(Status.equals("未到诊")){
            String str = "已完成";
            orderDao.changeOrderStatus(str,id);
        }else if(Status.equals("已完成")){
            String str ="未到诊";
            orderDao.changeOrderStatus(str,id);
        }
    }

    //根据会员id获取套餐id
    @Override
    public List<Integer> findSetmealIdByMemberId(Integer id) {
        return orderDao.findSetmealIdByMemberId(id);
    }
}
